﻿using System;
using System.IO;

namespace KKCai.Html
{
    internal class Filter : Stream
    {
        private Stream _sink;
        private FileStream _fs;

        public Filter(Stream sink, string filePath)
        {
            string dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            _sink = sink;
            _fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override void Flush()
        {
            _sink.Flush();
        }

        public override long Length
        {
            get { return 0; }
        }

        public override long Position { get; set; }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _sink.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return 0;
        }

        public override void SetLength(long value)
        {
            _sink.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _sink.Write(buffer, offset, count);

            _fs.Write(buffer, offset, count);
        }

        public override void Close()
        {
            _sink.Close();

            _fs.Close();
        }
    }
}
